package com.springboot.demo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.springboot.demo.dao.UserMapper;
import com.springboot.demo.domain.User;
import com.springboot.demo.domain.UserExample;
import com.springboot.demo.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

//把spring容器中的bean进行实例化，也就是等同于new操作，
@Service
public class UserManagerImpl implements UserManager {

    //自动导入依赖的bean
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean save(User user) {
        user.setUserId(UUID.randomUUID().toString().replace("-",""));
        user.setStatus("NORMAL");
        user.setDateAdded(new Date());
        user.setPasswd("123456");
        return userMapper.insertSelective(user) > 0;
    }

    @Override
    public boolean remove(String id) {

        User user = new User();
        user.setUserId(id);
        user.setStatus("FROZEN");

        return userMapper.updateByPrimaryKeySelective(user) > 0;
    }

    @Override
    @Transactional
    public boolean batchRemove(String[] ids) {

        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.or();
        criteria.andUserIdIn(Arrays.asList(ids));

        User user = new User();
        user.setStatus("FROZEN");

        return userMapper.updateByExampleSelective(user,example) > 0;
    }

    @Override
    public boolean updateUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user) > 0;
    }

    @Override
    public User getUser(String userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public PageInfo<User> getUserList(int limit, int offset, String nickName, String statu) {

        PageHelper.offsetPage(offset,limit);

        UserExample example = new UserExample();
        UserExample.Criteria Criteria = example.or();
        if("" != nickName && null != nickName){
            Criteria.andNicknameLike(nickName + "%");
        }
        example.setOrderByClause("date_added desc");

        List<User> userList = userMapper.selectByExample(example);
        PageInfo<User> pageInfo= new PageInfo<User>(userList);

        return pageInfo;
    }
}
